package org.example.myleet.p481;

public class Solution {
    public int magicalString(int n) {
        StringBuilder sb = new StringBuilder();
        sb.append("122");
        int oneCount = 1;
        int p1 = 2;
        boolean odd = true;
        while (true) {
            if (sb.length() >= n) {
                return oneCount;
            }
            int cnt = sb.charAt(p1) - '0';
            for (int i = 0; i < cnt; ++i) {
                if (odd) {
                    ++oneCount;
                }
                sb.append(odd ? 1 : 2);
                if (sb.length() >= n) {
                    return oneCount;
                }
            }
            ++p1;
            odd = !odd;
        }
    }
}
